import cn.leancloud.LCObject;
import cn.leancloud.core.LeanCloud;
import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;
import javafx.stage.StageStyle;
import page.mainPage.LoginPage;
import page.mainPage.MainPage;
import utils.ControllerUtils;
import utils.DBUtils;
import utils.GlobalVar;

import java.io.IOException;

public class MainUi extends Application {
    public static void run(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {
        LeanCloud.initialize("UVAmxh5Nv40Kbgv9lbzVN2F9-gzGzoHsz", "Xb83dnb7aZpGbL4E9qJwrqVE", "https://uvamxh5n.lc-cn-n1-shared.com");
        System.out.println("尝试使用 session 登陆...");
        DBUtils dbUtils = new DBUtils();
        FXMLLoader loader;
        Scene scene;
        // 使用 session 登陆
        if (dbUtils.loginWithSession()) {
            System.out.println("用户已经登陆，跳转到首页");
            // 跳转到主页
            loader = new FXMLLoader(MainPage.class.getResource("MainPage.fxml"));
            GlobalVar.loader = loader;
            try {
                Parent root = loader.load();
                scene = new Scene(root);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }

        } else {
            System.out.println("session 不合法，跳转登陆页");
            loader = ControllerUtils.getLoaderFromFxml(LoginPage.class.getResource("LoginPage.fxml"));
            stage.initStyle(StageStyle.TRANSPARENT);
            scene = LoginPage.createScene(loader);
        }
        stage.setScene(scene);
        stage.show();

    }

    @Override
    public void stop() {
        // 保存全局数据
        GlobalVar.getLcGlobalMap().values().forEach(LCObject::save);
    }
}